package com.songxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songxh.dto.DishDto;
import com.songxh.mapper.DishMapper;
import com.songxh.pojo.Dish;
import com.songxh.pojo.DishFlavor;
import com.songxh.service.DishFlavorService;
import com.songxh.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author songxh
 * @create 2022-04-24-19:24
 */
@Service
@Transactional
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品，并保存口味的数据
     * 可以理解为 后台管理员添加一个菜品，并设置该菜品有哪些口味
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);

        //获取前台传来的菜品的id
        Long dtoId = dishDto.getId();

        //遍历DishFlavor集合，将他们的菜品id即dishid赋值
        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setDishId(dtoId);
        }

        //将菜品的口味保存到dishFlavor中
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }


    /**
     * 根据id来查询菜品信息和口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(long id) {
        //查询口味信息
        QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        //查询基本信息
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();

        //将dish中的基本信息拷贝到dishDto中
        BeanUtils.copyProperties(dish,dishDto);
        //设置口味信息
        dishDto.setFlavors(list);

        return dishDto;
    }


    /**
     * 更新菜品表和口味表
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新DishFlavor表
        Long dishId = dishDto.getId();//获取dish的id
        QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",dishId);
        //先将其删除
        dishFlavorService.remove(queryWrapper);

        //在将修改后的内容传进去
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历DishFlavor集合，将他们的菜品id即dishid赋值
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        //将该集合保存到DishFlavor表中
        dishFlavorService.saveBatch(flavors);

        //更新dish表
        this.updateById(dishDto);
    }
}
